﻿#region Copyright (c) 2013-04, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Reflection;
using System.Threading.Tasks;


namespace Amarok.Agents
{
	/// <summary>
	/// </summary>
	internal sealed class OperationHandlerInspector : HandlerInspector
	{
		#region ++ Public Interface ++

		/// <summary>
		/// </summary>
		public override HandlerInfo Inspect(MethodInfo methodInfo)
		{
			if (OperationHandlerAttribute.IsDefined(methodInfo) == false)
				return null;

			if (VerifyNotGeneric(methodInfo) == false)
				return null;

			var parameters = methodInfo.GetParameters();

			if (VerifyParameterCount(methodInfo, parameters) == false)
				return null;

			var parameter = parameters[0];

			if (VerifyIsOperationTypeParameter(methodInfo, parameter) == false)
				return null;

			var result = _GetOperationResultAndProgressType(parameter);
			var resultType = result.Item1;
			var progressType = result.Item2;

			if (VerifyIsGenericOperationTypeParameter(methodInfo, resultType) == false)
				return null;

			var isAsync = IsAsync(methodInfo);

			if (isAsync)
			{
				var taskResultType = _GetMethodTaskResultType(methodInfo);

				if (VerifyAsyncOperationResultType(methodInfo, resultType, taskResultType) == false)
					return null;
			}
			else
			{
				if (VerifyOperationResultType(methodInfo, resultType) == false)
					return null;
			}

			return new OperationHandlerInfo(methodInfo, parameter, isAsync, resultType, progressType);
		}

		#endregion

		#region Implementation

		private Boolean VerifyIsGenericOperationTypeParameter(MethodInfo methodInfo, Type resultType)
		{
			if (resultType != null)
				return true;

			ReportInvalidHandler(methodInfo,
				"The method parameter type is not derived from 'Amarok.Agents.Operation<TResult, TProgress>'.");

			return false;
		}

		private Boolean VerifyOperationResultType(MethodInfo methodInfo, Type resultType)
		{
			if (methodInfo.ReturnType == resultType)
				return true;
			if (resultType.IsAssignableFrom(methodInfo.ReturnType))
				return true;

			ReportInvalidHandler(methodInfo,
				"The method return type does not match the operation result type.");

			return false;
		}

		private Boolean VerifyAsyncOperationResultType(MethodInfo methodInfo, Type resultType, Type taskResultType)
		{
			if (taskResultType == null)
			{
				ReportInvalidHandler(methodInfo,
					"Async methods with return types other than 'System.Threading.Tasks.Task<T>' are not supported.");

				return false;
			}
			else
			{
				if (taskResultType == resultType)
					return true;

				ReportInvalidHandler(methodInfo,
					"The method return type does not match the operation result type.");

				return false;
			}
		}

		private static Tuple<Type, Type> _GetOperationResultAndProgressType(ParameterInfo parameter)
		{
			var type = parameter.ParameterType;

			while (type != null)
			{
				if (type == typeof(Operation))
					break;

				if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Operation<,>))
				{
					var genericArgumentTypes = type.GetGenericArguments();

					return new Tuple<Type, Type>(
						genericArgumentTypes[0],	// result type
						genericArgumentTypes[1]);	// progress type
				}

				type = type.BaseType;
			}

			return new Tuple<Type, Type>(null, null);
		}

		private static Type _GetMethodTaskResultType(MethodInfo methodInfo)
		{
			var type = methodInfo.ReturnType;

			while (type != null)
			{
				if (type == typeof(Task))
					break;

				if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Task<>))
				{
					var genericArgumentTypes = type.GetGenericArguments();
					return genericArgumentTypes[0];	// task result type
				}

				type = type.BaseType;
			}

			return null;
		}

		#endregion

	}
}
